import json
import numpy
from bean.hot_new import HotNew
from bean.hot_new_message import HotNewMessage
from bean.hot_new_type import HotNewType


class HotNewsEncoder(json.JSONEncoder):

    def default(self, obj):
        if isinstance(obj, numpy.ndarray):
            return obj.tolist()
        elif isinstance(obj, bytes):
            return str(obj, encoding='utf-8')
        elif isinstance(obj, int):
            return str(obj)
        elif isinstance(obj, HotNew):
            res = {}
            for f in dir(obj):
                value = getattr(obj, f)
                if not f.startswith("__") and not callable(value):
                    res[f] = value
            return res
        elif isinstance(obj, HotNewType):
            res = {}
            for f in dir(obj):
                value = getattr(obj, f)
                if not f.startswith("__") and not callable(value):
                    res[f] = value
            return res
        elif isinstance(obj, HotNewMessage):
            res = {}
            for f in dir(obj):
                value = getattr(obj, f)
                res_list = []
                if not f.startswith("__") and not callable(value):
                    print(type(value))
                    if isinstance(value, str):
                        res[f] = value
                    elif isinstance(value, int):
                        res[f] = str(value)
                    elif isinstance(value, list):
                        for value_item in value:
                            res2 = {}
                            for ff in dir(value_item):
                                value2 = getattr(value_item, ff)
                                if not ff.startswith("__") and not callable(value2):
                                    res2[ff] = value2
                            res_list.append(res2)
                        res[f] = res_list
                    else:
                        res[f] = ''
            return res
        return json.JSONEncoder.default(self, obj)
